/**
 * Created by guomin on 2017/5/15.
 */
var validator=require('validator');
var initPool=require('../common/initPool');
var checkParams=require('../common/checkParams');
var getData=require('../common/getData');
var jsonWrite=require('../conf/response');

var resMsg=function(code,params){
    switch (code){
        case 0:return "success";break;
        case 101:return "参数不全";break;
        case 102:return "参数格式错误";break;
        case 105:return "参数为空";break;
        case 201:return "服务端异常";break;
        case 207:return "感谢信不存在";break;
        default:return "其它错误";break;
    }
};

module.exports={
    getLetterList:function(req,res){
        var date=new Date();
        var params=req.query;
        checkParams.isDefined(params,["pageNow","pageSize"]).then(function(){
            return checkParams.isParamsEmpty(params,["pageNow","pageSize"]);
        }).then(function(){
            return checkParams.isRightFormat(params,["pageNow","pageSize"]);
        }).then(function(){
            return initPool();
        }).then(function(connection){
            return getData.getLetterList(connection,params);
        }).then(function(result){
            jsonWrite(res,{"status":0,"msg":resMsg(0),"result":result,"time":date.toLocaleString()});
        }).catch(function(err){
            if(err){
                var isInt=validator.isInt(err.toString());
                if(isInt){
                    jsonWrite(res,{"status":err,"msg":resMsg(err,params),"time":date.toLocaleString()});
                }else{
                    jsonWrite(res,{"status":201,"msg":resMsg(201),"time":date.toLocaleString()});
                    throw err;
                }
            }
        });
    }
    ,
    getLetterDetail:function(req,res){
        var date=new Date();
        var params=req.query;
        checkParams.isDefined(params,["id"]).then(function(){
            return checkParams.isParamsEmpty(params,["id"]);
        }).then(function(){
            return checkParams.isRightFormat(params,["id"]);
        }).then(function(){
            return initPool();
        }).then(function(connection){
            return getData.getLetterDetail(connection,params);
        }).then(function(result){
            jsonWrite(res,{"status":0,"msg":resMsg(0),"result":result,"time":date.toLocaleString()});
        }).catch(function(err){
            if(err){
                var isInt=validator.isInt(err.toString());
                if(isInt){
                    jsonWrite(res,{"status":err,"msg":resMsg(err,params),"time":date.toLocaleString()});
                }else{
                    jsonWrite(res,{"status":201,"msg":resMsg(201),"time":date.toLocaleString()});
                    throw err;
                }
            }
        });
    }

};